package dao.Card;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.Card;
import abstractFactory.Factory;

public class CardDAOJPA implements CardDAO{
	static EntityManager manager;

	public EntityManager getManager() {
		if(manager == null) {
			manager = Factory.getFactory().createEntityManager();
		}
		return manager;
	}

	public boolean save(Card card) {
		try	{
			getManager().getTransaction().begin();
			getManager().persist(card);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean update(Card card){
		try{
			getManager().getTransaction().begin();
			getManager().merge(card);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean delete(Card card){
		try {
			getManager().getTransaction().begin();
			Card c = getManager().find(Card.class,card.getId());
			getManager().remove(c);
			getManager().getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public List<Card> getAllCards(){
		Query query = (Query) getManager().createQuery("SELECT c FROM Card c where c.active = 1" );
		@SuppressWarnings("unchecked")
		List<Card> Cards =  query.getResultList();
		return Cards;
	}

	public Card getCardById(int cardId){
		try {
			Card card = getManager().find(Card.class, cardId);
			return card;
		} 
		catch (Exception e) {	
			return null;				
		}
	}

	public Long getTotalCards(){
		Query query = (Query) getManager().createQuery("SELECT count(c) FROM Card c where c.active = 1" );
		Long total = (Long) query.getSingleResult();
		return total;
	}
}
